#!/bin/bash -x
set -x
ProgName=$(basename $0)
BaseDir=$(dirname $(readlink -f "$0"))
SYSOM_UNINSTALL_LOG=$LOG_HOME/sysom_uninstall.log

####################################################################################################################
# Helper functions
####################################################################################################################

red() {
    printf '\33[1;31m%b\n\33[0m' "$1"
}

green() {
    printf '\33[1;32m%b\n\33[0m' "$1"
}

do_uninstall_environment() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for env in $(ls ${ENVIRONMENT_HOME} | grep ${target}); do
            target_dir=${ENVIRONMENT_HOME}/${env}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/uninstall.sh" ]; then
                continue
            fi

            pushd ${target_dir}
            green "$target_dir uninstall..................................."
            bash -x ${target_dir}/uninstall.sh
            if [ $? -ne 0 ]; then
                red "$target_dir uninstall fail, please check..................................."
                exit 1
            fi
            popd

            # rm dir
            rm -rf ${target_dir}
        done
    done

    # rm env if the folder is empty
    if [ "$(ls ${ENVIRONMENT_HOME} | wc -l)" == "0" ]; then
        rm -rf ${ENVIRONMENT_HOME}
    fi
}

do_uninstall_microservice() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for service in $(ls ${MICROSERVICE_HOME} | grep ${target}); do
            target_script_dir=${MICROSERVICE_SCRIPT_HOME}/${service}
            target_service_dir=${MICROSERVICE_HOME}/${service}
            if [ ! -d "$target_script_dir" ] || [ ! -f "${target_script_dir}/uninstall.sh" ]; then
                continue
            fi
            pushd ${target_script_dir}

            green "$target_script_dir uninstall..................................."
            bash -x ${target_script_dir}/uninstall.sh
            if [ $? -ne 0 ]; then
                red "$target_script_dir uninstall fail, please check..................................."
                red "sysom uninstall failed, exit 1"
                exit 1
            fi
            popd

            # rm dir
            rm -rf ${target_script_dir}
            rm -rf ${target_service_dir}
        done
    done

    dircount=$(ls -l ${MICROSERVICE_HOME} | grep "^d" | wc -l)
    # rm env if the folder is empty
    if [ "$dircount" == "0" ]; then
        rm -rf ${MICROSERVICE_HOME}
    else
        if [ "$dircount" == "1" ] && [ -d "${MICROSERVICE_HOME}/conf" ]; then
            rm -rf ${MICROSERVICE_HOME}
        fi
    fi
}

do_uninstall_deps() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for dep in $(ls ${DEPS_HOME} | grep ${target}); do
            target_dir=${DEPS_HOME}/${dep}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/uninstall.sh" ]; then
                continue
            fi

            pushd ${target_dir}
            green "$target_dir uninstall..................................."
            bash -x ${target_dir}/uninstall.sh
            if [ $? -ne 0 ]; then
                red "$target_dir uninstall fail, please check..................................."
                red "sysom uninstall failed, exit 1"
                exit 1
            fi
            popd

            # rm dir
            rm -rf ${target_dir}
        done
    done

    # rm env if the folder is empty
    if [ "$(ls ${DEPS_HOME} | wc -l)" == "0" ]; then
        rm -rf ${DEPS_HOME}
    fi
}

check_and_rm_server_home() {
    # Whether delete SERVER_HOME
    if [ -d "${SERVER_HOME}" ] && [ "`ls -A ${SERVER_HOME}`" = "" ];then
        rm -r ${SERVER_HOME}
    fi
}

check_and_rm_app_home() {
    # Whether delete APP_HOME
    if [ -d "${APP_HOME}" ] && [ "`ls -A ${APP_HOME}`" = "init_scripts" ]; then
        rm -r ${APP_HOME}
    fi
}

####################################################################################################################
# Subcommands
####################################################################################################################

sub_help() {
    echo "Usage: $ProgName <subcommand> [options]"
    echo "Subcommands:"
    echo "    all                                           Uninstall all modules"
    echo "    env   [ALL | <base_env_name>]                 Uninstall all enviroment or specific enviroment"
    echo "          Example: $ProgName env env"
    echo "          Example: $ProgName env sdk"
    echo "    deps  [ALL | <deps_name>]                     Uninstall all deps or specific dep"
    echo "          Example: $ProgName dep mysql"
    echo "          Example: $ProgName dep grafana"
    echo "    ms    [ALL | <service_name>]                  Uninstall all microservices or specific microservice"
    echo "          Example: $ProgName ms sysom_diagnosis"
    echo ""
    echo "For help with each subcommand run:"
    echo "$ProgName <subcommand> -h|--help"
    echo ""
}

sub_ALL() {
    sub_web
    sub_ms ALL
    sub_env ALL
    sub_deps ALL
}

sub_all() {
    sub_ALL
}

sub_env() {
    sub_environment $@
}

# -> env + sdk
sub_environment() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # Uninstall all microservices
        for env in $(ls -r $ENVIRONMENT_HOME); do
            if [ ! -d "${ENVIRONMENT_HOME}/${env}" ]; then
                continue
            fi
            do_uninstall_environment $env
        done
    else
        # Uninstall specific microservices
        do_uninstall_environment $target
    fi
}

sub_ms() {
    sub_microservice $@
}

# All microservices
sub_microservice() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # Uninstall all microservices
        for microservice in $(ls -r $MICROSERVICE_HOME); do
            if [ ! -d "${MICROSERVICE_HOME}/${microservice}" ]; then
                continue
            fi
            do_uninstall_microservice ${microservice}
        done
    else
        # Uninstall specific microservices
        do_uninstall_microservice $target
    fi
}

sub_deps() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # Uninstall all deps
        for dep in $(ls -r $DEPS_HOME); do
            if [ ! -d "${DEPS_HOME}/${dep}" ]; then
                continue
            fi
            do_uninstall_deps ${dep}
        done
    else
        # Uninstall specific dep
        do_uninstall_deps $target
    fi
}

# Uninstall web
sub_web() {
    rm -rf ${WEB_HOME}
}

subcommand=$1
case $subcommand in
"" | "-h" | "--help")
    sub_help
    ;;
*)
    shift
    sub_${subcommand} $@ | tee ${SYSOM_UNINSTALL_LOG}
    check_and_rm_server_home | tee ${SYSOM_UNINSTALL_LOG}
    check_and_rm_app_home | tee ${SYSOM_UNINSTALL_LOG}
    if [ $? = 127 ]; then
        echo "Error: '$subcommand' is not a known subcommand." >&2
        echo "       Run '$ProgName --help' for a list of known subcommands." >&2
        exit 1
    fi
    ;;
esac
